package com.qf.jie.service.impl;

import com.qf.jie.dao.CommentDao;
import com.qf.jie.dao.CommodityDao;
import com.qf.jie.dao.impl.CommentDaoImpl;
import com.qf.jie.dao.impl.CommodityDaoImpl;
import com.qf.jie.entity.bo.CommodityAndCommentBo;
import com.qf.jie.entity.bo.Page;
import com.qf.jie.entity.po.Comment;
import com.qf.jie.entity.po.Commodity;
import com.qf.jie.entity.po.User;
import com.qf.jie.entity.vo.RespBean;
import com.qf.jie.service.CommodityService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.util.Date;
import java.util.List;

public class CommodityServiceImpl implements CommodityService {
    CommodityDao commodityDao = new CommodityDaoImpl();
    CommentDao commentDao = new CommentDaoImpl();

    // 分页展示商品
    @Override
    public RespBean getPage(Object currentPage, Object len) {
        // 当前页(默认第一页)，
        int currentPage_Int = 1;
        // 每页长度(默认3条)
        int len_Int = 3;
        try {
            currentPage_Int = Integer.parseInt((String) currentPage);
            len_Int = Integer.parseInt((String) len);
        }catch (Exception e){
        }
        if (len_Int < 1 ){
            len_Int = 1;
        }
        // 数据总量
        int total = commodityDao.getCount();
        // 总页数
        int pageCount = (int)Math.ceil( (0.0+total)/len_Int);

        if (currentPage_Int < 1){
            currentPage_Int = 1;
        }else if (currentPage_Int > pageCount){
            currentPage_Int = pageCount;
        }

        // 要展示的数据
        List<Commodity> list = commodityDao.getList((currentPage_Int - 1) * len_Int, len_Int);


        Page page = new Page(total, len_Int, pageCount, currentPage_Int, list);
        return RespBean.respSuccess(page);
    }

    //展示商品，根据用户id（卖家查看自己店铺中的商品）
    @Override
    public RespBean getCommodityListByUserId(HttpServletRequest req) {
        User user = (User)req.getSession().getAttribute("user");
        Integer id = user.getId();
        List<Commodity> commodityList = commodityDao.getCommodityListByUserId(id);
        if (commodityList.size() == 0){
            return RespBean.respError("未获取到任何商品信息");
        }
        return RespBean.respSuccess(commodityList);
    }

    //增加商品
    @Override
    public RespBean addCommodity(HttpServletRequest req, Part part, String name, String strStock, String strPrice) {
        User user = (User)req.getSession().getAttribute("user");
        Integer user_type = user.getUser_type();
        if (user_type == 0){
            return RespBean.respError("当前账号不是卖家");
        }
        Integer user_id = user.getId();
        try{
            if (name.trim().equals("")){
                return RespBean.respError("商品名不能为空");
            }
            int stock = Integer.parseInt(strStock);
            double price = Double.parseDouble(strPrice);

            String img_path = "/asserts/img/" ;
            String img_name = new Date().getTime() + part.getSubmittedFileName();
            String img_url = img_path  + img_name;
            part.write(req.getServletContext().getRealPath(img_url));

            Commodity commodity = new Commodity(0, name, req.getContextPath()+img_url, stock, price, user_id);
            int num = commodityDao.addBean(commodity);
            if (num == 0){
                return RespBean.respError("添加失败，未知错误");
            }
            return RespBean.respSuccess("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.respError("传入参数异常");
        }
    }
    // 删除商品
    @Override
    public RespBean deleteCommodityById(HttpServletRequest req, String strId) {
        User user = (User) req.getSession().getAttribute("user");
        Integer user_id = user.getId();
        int id = Integer.parseInt(strId);
        //卖家只能删除自己的商品
        int num = commodityDao.deleteByIdAndUserId(id, user_id);
        if (num == 0){
            return RespBean.respError("删除失败，未知错误");
        }
        return RespBean.respSuccess("删除成功");
    }

    // 修改商品信息
    @Override
    public RespBean updateCommodityById(HttpServletRequest req, String strId, String name, String strStock, String strPrice) {
        User user = (User)req.getSession().getAttribute("user");
        int user_id = user.getId();
        try{
            if (name.trim().equals("")){
                return RespBean.respError("商品名不能为空");
            }
            int id = Integer.parseInt(strId);
            int stock = Integer.parseInt(strStock);
            double price = Double.parseDouble(strPrice);

            List<Commodity> commoditys = commodityDao.getBeanById(id);
            if (commoditys.size() == 0 || commoditys.get(0).getUser_id() != user_id){
                System.out.println(commoditys);
                return RespBean.respError("只能修改自己的商品");
            }

            Commodity commodity = new Commodity(id, name, commoditys.get(0).getImg_url(), stock, price, user_id);
            int num = commodityDao.updateById(commodity);
            if (num == 0){
                return RespBean.respError("修改失败，未知错误");
            }
            return RespBean.respSuccess("修改成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.respError("传入参数异常");
        }
    }

    // 更改图片
    @Override
    public RespBean updateCommodityImgById(HttpServletRequest req, Part part, String strId) {
        User user = (User) req.getSession().getAttribute("user");
        try{
            String img_path = "/asserts/img/" ;
            String img_name = new Date().getTime() + part.getSubmittedFileName();
            String img_url = img_path  + img_name;
            part.write(req.getServletContext().getRealPath(img_url));

            int id = Integer.parseInt(strId);
            List<Commodity> commoditys = commodityDao.getBeanById(id);
            if (commoditys.size() == 0){
                return RespBean.respError("该商品已不存在");
            }
            commoditys.get(0).setImg_url(req.getContextPath()+img_url);
            int num = commodityDao.updateById(commoditys.get(0));
            if (num == 0){
                return RespBean.respError("更改图片失败，未知错误");
            }
            return RespBean.respSuccess("更改图片成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.respError("传入参数异常");
        }
    }

    //商品详情（显示评论）
    @Override
    public RespBean CommodityDetailed(String strCommodity_id){
        try {
            int commodity_id = Integer.parseInt(strCommodity_id);
            List<Commodity> commodities = commodityDao.getBeanById(commodity_id);
            List<Comment> comments = commentDao.getListByCommodity_id(commodity_id);
            CommodityAndCommentBo commodityAndCommentBo = new CommodityAndCommentBo(commodities.get(0), comments);
            return RespBean.respSuccess(commodityAndCommentBo);
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.respError("参数异常：参数commodity_id=" + strCommodity_id + "无法识别");
        }
    }
    // 添加评论
    @Override
    public RespBean addComment(HttpServletRequest req, String strCommodity_id, String text) {
        try{
            int commodity_id = Integer.parseInt(strCommodity_id);
            if (text.equals("")){
                return RespBean.respError("评论不能为空");
            }
            User user = (User)req.getSession().getAttribute("user");
            int user_id = user.getId();
            Comment comment = new Comment(0, user_id, text, commodity_id);
            int num = commentDao.addBean(comment);
            if (num == 0){
                return RespBean.respError("评论发送失败，未知错误");
            }
            return RespBean.respSuccess("发送成功");
        }catch (Exception e){
            e.printStackTrace();
            return RespBean.respError("参数异常：commodity_id=" + strCommodity_id + ", text=" +text);
        }
    }

    @Override
    public RespBean login(HttpServletRequest request, String name, String password) {
        return null;
    }

    @Override
    public RespBean register(Commodity commodity) {
        return null;
    }


}
